package com.zmn.oms.zmn.business.impl.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.company.CompanyListRemoteService;
import com.zmn.base.pilot.common.dto.pilot.PilotCheckQuery;
import com.zmn.base.pilot.common.enums.PilotTypeEnum;
import com.zmn.base.price.common.dto.item.ItemCellDRO;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.price.common.dto.item.ItemQuoteQuery;
import com.zmn.base.price.dubbo.interfaces.calculate.ItemPriceRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.gms.common.company.CompanyGridInfoDIO;
import com.zmn.gms.common.company.CompanyGridInfoDRO;
import com.zmn.gms.common.dto.online.grid.GridSpDRO;
import com.zmn.gms.dubbo.interfaces.grid.online.company.CompanyGridListRemoteService;
import com.zmn.gms.dubbo.interfaces.grid.online.order.GridOrderListRemoteService;
import com.zmn.manager.redis.RedisManager;
import com.zmn.mos.common.dio.order.add.nest.UserDIO;
import com.zmn.oms.business.impl.order.OrderBaseBServiceImpl;
import com.zmn.oms.business.interfaces.discount.OrderDiscountBService;
import com.zmn.oms.business.interfaces.messageV1.app.MessageSendAppService;
import com.zmn.oms.business.interfaces.operator.OrderWorkOperatorBService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountCalcBService;
import com.zmn.oms.business.interfaces.orderstock.OrderStockBService;
import com.zmn.oms.business.interfaces.serviceitem.OrderServiceItemBService;
import com.zmn.oms.business.interfaces.xno.OrderXnoBindBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.GridCompanyQueryBO;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.bo.order.VerifyOrderBO;
import com.zmn.oms.model.bo.orderamount.OrderAmountCalcBO;
import com.zmn.oms.model.bo.orderamount.ReCalcOrderAmountDIO;
import com.zmn.oms.model.dto.operator.OrderWorkOperatorDTO;
import com.zmn.oms.model.dto.order.ConfirmDTO;
import com.zmn.oms.model.dto.order.GridCompanyInfoDTO;
import com.zmn.oms.model.dto.order.NonClaimOrderDTO;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.dto.orderstock.LockStockDTO;
import com.zmn.oms.model.dto.orderstock.ReleaseStockDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.dto.serviceitem.AddOrderServiceItemDTO;
import com.zmn.oms.model.dto.tag.OrderTagDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyDutyTimeDTO;
import com.zmn.oms.model.dto.work.modify.CheckQuotationTypeOrderDTO;
import com.zmn.oms.model.dto.work.modify.ProductTaraiffIdDTO;
import com.zmn.oms.model.dto.work.modify.must.OrderWorkGrabDTO;
import com.zmn.oms.model.dto.work.xno.XnoBindDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.grab.NonGridGrabOrder;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.order.NonClaimOrder;
import com.zmn.oms.model.entity.order.OrderServiceReason;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotation;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.quotation3.OrderQuotationServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItemCell;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.query.grab.NonGridGrabOrderQuery;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.conf.workturn.bizmode.PlatBizModeService;
import com.zmn.oms.services.interfaces.grab.NonGridGrabOrderService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.order.NonClaimOrderService;
import com.zmn.oms.services.interfaces.order.OrderServiceReasonService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.grab.NonGridGrabOrderBService;
import com.zmn.oms.zmn.business.interfaces.order.ZsOrderBService;
import com.zmn.oms.zmn.business.interfaces.quotation3.OrderQuotation3ModifyBService;
import com.zmn.oms.zmn.business.interfaces.wallquotation.WallQuotationBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkGrabBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsCustomWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import com.zmn.sp.common.model.manage.SpServProviderDRO;
import com.zmn.sp.common.model.manage.SpServProviderQuery;
import com.zmn.sp.dubbo.interfaces.manage.SpManageListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.zmn.base.common.data.common.constant.CompanyConst;

/**
 * 类描述：工单
 *
 * @author liuying
 * @date 2018/12/13 19:47
 */
@Slf4j
@Service
public class ZsOrderBServiceImpl extends OrderBaseBServiceImpl implements ZsOrderBService {

    @Reference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private GridOrderListRemoteService gridOrderListRemoteService;
    @Reference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private CompanyGridListRemoteService companyGridListRemoteService;
    @Reference(version = com.zmn.sp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private SpManageListRemoteService spManageListRemoteService;
    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private CompanyListRemoteService companyListRemoteService;
    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private ItemPriceRemoteService itemPriceRemoteService;


    @Autowired
    private ZsCustomWorkBService zsCustomWorkBService;
    @Autowired
    private OrderServiceItemBService orderServiceItemBService;
    @Autowired
    private OrderMemberService orderMemberService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderXnoBindBService orderXnoBindBService;
    @Autowired
    private OrderAmountCalcBService orderAmountCalcBService;
    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;
    @Autowired
    private NonClaimOrderService nonClaimOrderService;
    @Autowired
    private OrderVerifyBServiceImpl verifyOrderBService;
    @Autowired
    OrderWorkGrabBService orderWorkGrabBService;
    @Autowired
    OrderStockBService orderStockBService;
    @Autowired
    OrderQuotation3ModifyBService orderQuotation3ModifyBService;
    @Autowired
    OrderWorkOperatorBService orderWorkOperatorBService;
    @Autowired
    OrderDiscountBService orderDiscountBService;
    @Autowired
    private OrderServiceReasonService orderServiceReasonService;
    @Autowired
    private OrderTagService orderTagService;
    @Autowired
    private ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    private MessageSendAppService messageSendAppService;
    @Autowired
    private ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    private NonGridGrabOrderService nonGridGrabOrderService;
    @Autowired
    private NonGridGrabOrderBService nonGridGrabOrderBService;
    @Resource
    private WallQuotationBService wallQuotationBService;
    @Resource
    private RedisManager redisManager;
    @Resource
    private PlatBizModeService platBizModeService;
    @Resource
    private ZsNormalOrderServiceItemBService zsNormalOrderServiceItemBService;

    /**
     * 取消缘由
     */
    @NacosValue(value = "${order.add.check.fail.id:0}", autoRefreshed = true)
    private List<Integer> failMapIdList;

    /**
     * 简单确认---确认待重构
     * 自动确认
     * @param confirmDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_CONFIRM)
    public void confirmOrderSimple(ConfirmDTO confirmDTO) {
        OrderWork orderWork = BeanMapper.map(confirmDTO, OrderWork.class);
        orderWorkService.updateConfirm(orderWork);
    }

    /**
     * 手动确认
     * @param orderDTO
     * @return OrderBO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_CONFIRM, beforeProceed = false)
    public OrderBO confirmOrder(OrderDTO orderDTO) throws OmsBaseException {
        return this.updateOrder(orderDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_UPDATE, beforeProceed = false)
    public OrderBO updateOrder(OrderDTO orderDTO) throws OmsBaseException {

        // 订单信息
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderFactory orderFactory = orderDTO.getOrderFactory();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        OrderDetail orderDetail = orderDTO.getOrderDetail();


        // 检验是否能修改墙面订单
        wallQuotationBService.checkUpdateWallOrder(PilotCheckQuery.builder()
                .categId(orderWork.getShowCategId())
                .channelId(orderWork.getChannelId())
                .cityId(orderWork.getCityId())
                .servCategId(orderWork.getServCategId())
                .pilotTypeId(PilotTypeEnum.WALL_QUOTE.getId())
                .build(),orderWork.getServProductGroupId(),orderWork.getServItemType(),orderWork.getWorkId());

        // 原始数据
        OrderWork dbOrderWork = Optional.ofNullable(orderDTO.getDbOrderWork())
                .orElse(orderWorkService.findOrderWorkByKey(orderWork.getOrderId(), orderWork.getWorkId()));
        OrderFactory dbOrderFactory = Optional.ofNullable(orderDTO.getDbOrderFactory())
                .orElse(orderFactoryService.findOrderFactoryByKey(orderWork.getOrderId()));
        List<OrderProduct> dbOrderProductList = Optional.ofNullable(orderDTO.getDbOrderProductList())
                .orElse(orderProductService.listOrderProductByOrderId(orderWork.getOrderId()));
        OrderDetail dbOrderWorkDetail = Optional.ofNullable(orderDTO.getDbOrderDetail())
                .orElse(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()));

        // 业务类型不能变更
        orderWork.setBizType(dbOrderWork.getBizType());
        boolean isMember = dbOrderWork.getMember() != null && Objects.equals(dbOrderWork.getMember(), GlobalConsts.YES);
        OrderMember dbOrderMember = null;
        if (isMember) {
            if (orderDTO.getDbOrderMember() == null) {
                dbOrderMember = orderMemberService.findMemberByKey(orderWork.getOrderId());
            }
            orderDTO.setDbOrderMember(dbOrderMember);
        }

        // 产品ID是否变更
        boolean isProductIdChanged;
        // 产品数量变化
        boolean isProductNumberChanged;
        if (Objects.equals(dbOrderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_FACTORY)) {
            isProductIdChanged = ( !Objects.equals(dbOrderFactory.getFcProductId(), orderFactory.getFcProductId()) )
                    || ( !Objects.equals(dbOrderWork.getServCategId(), orderWork.getServCategId())
                    || !Objects.equals(orderWork.getProductId(), dbOrderWork.getProductId()) );
            isProductNumberChanged = !Objects.equals(Optional.ofNullable(dbOrderFactory.getFcProductNumber()).orElse(1),
                    orderFactory.getFcProductNumber());
        } else {
            isProductIdChanged = !Objects.equals(dbOrderWork.getProductId(), orderWork.getProductId()) || !Objects.equals(dbOrderWork.getShowProductId(), orderWork.getShowProductId());
            isProductNumberChanged = !Objects.equals(dbOrderProductList.get(0).getNumber(), orderProductList.get(0).getNumber());
        }
        // 前台产品ID是否变化
        boolean isShowProductIdChanged = !Objects.equals(dbOrderWork.getShowProductId(), orderWork.getShowProductId());

        // 渠道变化
        boolean channelChanged = !NumberUtil.isNullOrZero(orderWork.getChannelId()) && !Objects.equals(orderWork.getChannelId(), dbOrderWork.getChannelId());
        // 城市变化
        boolean cityChanged = !NumberUtil.isNullOrZero(orderWork.getCityId()) && !Objects.equals(orderWork.getCityId(), dbOrderWork.getCityId());
        // 产品变化
        boolean isProductChanged = isProductIdChanged || isProductNumberChanged;

        if (isProductChanged || channelChanged || cityChanged) {
            Integer brandId = null;
            if (!CollectionUtils.isEmpty(orderProductList)) {
                brandId = orderProductList.get(0).getBrandId();
            }
            if (brandId == null && !CollectionUtils.isEmpty(dbOrderProductList)) {
                brandId = dbOrderProductList.get(0).getBrandId();
            }
            orderWork.setProductBrandId(NumberUtil.isNullOrZero(brandId) ? null : brandId);
        }
        boolean isResetServiceItem = false;
        // 品牌是否变化
        boolean brandIdChanged = !Objects.equals(orderProductList.get(0).getBrandId(), dbOrderProductList.get(0).getBrandId());
        boolean isRework = Objects.equals(dbOrderWork.getType(), OrderConsts.ORDER_TYPE_REWORK) && Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK);

        // 计价器类型变化 品牌改变，品牌系数改变，非返修单，重新生成服务项价格
        if ((isShowProductIdChanged || channelChanged || cityChanged)) {
            // 更新服务项类型
            this.updateServiceItemType(orderWork, dbOrderWork);
            if (!isRework) {
                // 计价器类型变化，清空服务项
                orderServiceItemService.deleteByOrderId(orderWork.getOrderId());
                isResetServiceItem = true;
                // 计算和更新工单金额
                ReCalcOrderAmountDIO calcOrderAmountDIO = orderAmountCalcBService.getReCalcOrderAmountDIO(dbOrderWork);
                calcOrderAmountDIO.getOrderAmountDIO().setOriginalAmount(null);
                OrderAmountCalcBO orderAmountCalcBO = orderAmountCalcBService.reCalcOrderAmountAndDiscountAmount(TriggerAmountChangeEnum.DELETE_ORDER_AMOUNT, calcOrderAmountDIO, null);
                orderWorkAmountBService.updateAmountAndDiscount(orderAmountCalcBO,orderWork);
            }
        }

        // 工单类型变化 新单->返修/返修->新单 需要清空服务项
        boolean isTypeChange = this.isTypeChange(orderDTO);

        // 产品变更 或者 由（城市渠道变更导致 一口价标识变化）需要清空重置服务项，
        // 服务项类型改变也需要重新设置服务项/故障项
        // 影响故障项计价系数的相关信息改变也需要重新设置服务项
        boolean isCreateServiceItem = false;
        if (dbOrderWork.getStatus() < OrderStatusConsts.WORK_STATUS_COMPLETE) {
            isCreateServiceItem = isProductChanged || isTypeChange || channelChanged || cityChanged;
        }

        if (isCreateServiceItem && !isRework) {
            zsCustomWorkBService.updateCleanOrderAndAmount(dbOrderWork.getOrderId(), dbOrderWork.getWorkId(),
                    orderWork.getServCategId(), orderDTO);
            isResetServiceItem = true;
        }

        // 重新设置服务项
        if (isResetServiceItem) {
            // 清空报价信息
            String confirmQuotationRedisKey = String.format(RedisKeyConsts.USER_HAVE_CONFIRM_QUOTATION_KEY, String.valueOf(orderWork.getOrderId()));
            boolean isExistsConfirmQuotation = redisManager.exists(confirmQuotationRedisKey);
            if (isExistsConfirmQuotation) {
                redisManager.del(confirmQuotationRedisKey);
            }
            ProductTaraiffIdDTO productTaraiffIdDTO = ProductTaraiffIdDTO
                    .builder()
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .bizType(orderWork.getBizType())
                    .orderProductList(orderDTO.getOrderProductList())
                    .build();
            servItemBService.processProductTaraiffId(productTaraiffIdDTO);
        }else {
            // 价格表id
            Integer tariffId = dbOrderProductList.get(0).getTariffId();
            for (OrderProduct orderProduct : orderDTO.getOrderProductList()) {
                orderProduct.setTariffId(tariffId);
            }
            // 服务项类型
            orderWork.setServItemType(dbOrderWork.getServItemType());
        }

        // 如果是次卡订单，产品、城市、渠道等变化，判断优惠券是否继续满足使用
        if (!orderDiscountBService.checkTimesCoupCanUse(orderDTO)) {
            //如果不可用 退还优惠券 计算和更新工单金额
            ReCalcOrderAmountDIO calcOrderAmountDIO = orderAmountCalcBService.getReCalcOrderAmountDIO(dbOrderWork);
            OrderAmountCalcBO orderAmountCalcBO = orderAmountCalcBService.reCalcOrderAmountAndDiscountAmount(TriggerAmountChangeEnum.TIMES_DISCOUNT_DELETE, calcOrderAmountDIO, null);
            orderWorkAmountBService.updateAmountAndDiscount(orderAmountCalcBO, orderWork);
        }

        // 服务商派单修改不更新网格信息
        boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(orderWork);
        if (isGrid) {
            // 修改保存网格信息、行政服务商、行政子公司
            orderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
            this.saveGridInfo(orderDTO, OrderLogConsts.ORDER_LOG_TYPE_UPDATE);
        } else {
            orderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
        }

        // 保存订单信息
        logger.debug("修改模型orderDTO[{}]", orderDTO);
        OrderBO orderBO = orderBService.updateOrder(orderDTO);

        /*try {
            // 保存订单标签
            OrderTagDTO orderTagDTO = new OrderTagDTO();
            orderTagDTO.setOrderId(orderDTO.getOrderId());
            orderTagDTO.setWorkId(orderDTO.getWorkId());
            orderTagDTO.setOrderTagList(orderDTO.getOrderTagList());
            orderTagService.saveOrderTagList(orderTagDTO);
        } catch (Exception e) {
            logger.error("[{}]修改更新标签报错：【{}】", orderDTO.getOrderId(), e.getMessage());
        }*/

        // 派单、分单校验
        VerifyOrderBO verifyOrderBO = verifyOrderBService.verifyUpdateOrderAll(orderDTO, isGrid);
        // 分单撤回
        orderBO.setAssignBack(verifyOrderBO.getIsAssignBack());
        // 派单撤回
        orderBO.setDistributeBack(verifyOrderBO.getIsDistributeBack());

        // 修改预约时间
        orderWorkService.updateOrderWorkDutyTimeByKey(orderWork);

        // 判断是否交换工单预约信息
        if (Objects.nonNull(orderDTO.getExchangeWorkId())) {
            // 更新交换工单的预约信息
            ModifyDutyTimeDTO modifyDutyTimeDTO = new ModifyDutyTimeDTO();
            modifyDutyTimeDTO.setOrderId(orderDTO.getExchangeWorkId());
            modifyDutyTimeDTO.setWorkId(orderDTO.getExchangeWorkId());
            modifyDutyTimeDTO.setDutyTime(dbOrderWork.getDutyTime());
            modifyDutyTimeDTO.setOperatorId(orderDTO.getOperatorId());
            modifyDutyTimeDTO.setOperator(orderDTO.getOperator());
            modifyDutyTimeDTO.setOperatorType(orderDTO.getOperatorType());
            modifyDutyTimeDTO.setOperateTime(orderDTO.getOperateTime());
            zsOrderWorkBService.updateOrderDutyTime(modifyDutyTimeDTO);
            if (!orderStockBService.exChangeTwoOrderServTime(dbOrderWork.getMasterId(), orderWork.getWorkId(), orderDTO.getExchangeWorkId(), orderDTO.getOperator())) {
                throw new OmsBaseException("工程师预约库存对调失败!");
            }

            // 发送订单预约交换站内信
            this.sendOrderDutyExchangeAppMsg(orderDTO, orderWork, dbOrderWork);
        }else {
            // 重新占用库存（只有修改预约时间才去重新占用库存）
            boolean isUpdateDutyTime = Objects.nonNull(orderWork.getDutyTime()) && !orderWork.getDutyTime().equals(dbOrderWork.getDutyTime());
            if (isUpdateDutyTime) {
                LockStockDTO lockStockDTO = LockStockDTO.builder()
                        .orderId(dbOrderWork.getOrderId())
                        .workId(dbOrderWork.getWorkId()).build();
                orderStockBService.reLockEngStock(lockStockDTO);
            }
        }

        if (Objects.equals(orderWork.getTest(), GlobalConsts.YES)) {
            // 测试单，需要释放库存
            ReleaseStockDTO releaseStockDTO = new ReleaseStockDTO();
            releaseStockDTO.setOrderId(orderWork.getOrderId());
            releaseStockDTO.setWorkId(orderWork.getWorkId());
            releaseStockDTO.setMasterId(orderWork.getMasterId());
            releaseStockDTO.setCityId(orderWork.getCityId());
            orderStockBService.releaseStock(releaseStockDTO);
        }

        // 修改工程师主管
//        if (NumberUtil.isNotNullOrZero(dbOrderWork.getMasterId()) && !Objects.equals(orderWork.getServProductGroupId(), dbOrderWork.getServProductGroupId())) {
//            orderWorkBService.updateOrderMasterSupervisor(orderWork.getOrderId(), orderWork.getWorkId(), dbOrderWork.getMasterId(), dbOrderWork.getBizType(), orderWork.getServProductGroupId());
//        }

        // 返修变成新单，清空返修单号，源单号
        if (Objects.equals(dbOrderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)
                && Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            OrderWork updateOrerWork = new OrderWork();
            updateOrerWork.setOrderId(orderWork.getOrderId());
            updateOrerWork.setWorkId(orderWork.getWorkId());
            orderWorkService.updateCleanReworkByKey(updateOrerWork);
        }

        // 清空服务项后，重新设置服务项 （会校验一口价订单）
        // if (isCreateServiceItem) {
		//
        //     // 根据服务项获取订单金额
        //     Integer originalAmount = orderServiceItemBService.getServiceItemOriginalAmount(orderWork, orderProductList.get(0));
		//
        //     // 校验原价是否大于预付
        //     boolean validateOriginalAmount = true;
        //     if (originalAmount != null) {
        //         ValidateWorkAmountDTO validateWorkAmountDTO = new ValidateWorkAmountDTO();
        //         validateWorkAmountDTO.setOrderId(orderWork.getOrderId());
        //         validateWorkAmountDTO.setWorkId(orderWork.getWorkId());
        //         validateWorkAmountDTO.setOriginalAmount(originalAmount);
        //         validateOriginalAmount = orderWorkAmountBService.validateWorkAmount(validateWorkAmountDTO);
        //     }
		//
        //     // 重新设置所有服务项
        //     if (validateOriginalAmount) {
        //         orderServiceItemBService.resetServiceItemByUpdate(orderWork);
        //     }
		//
        //     // 原价验证失败，删除工程师收款、应收、优惠
        //     if (!validateOriginalAmount) {
        //         orderWorkAmountService.deleteOriginalAmount(orderWork.getOrderId(), orderWork.getWorkId());
        //     }
		//
        //     // 记录日志
        //     StringBuilder logRemark = new StringBuilder("变更产品，清空：已有服务项目和人工优惠");
        //     if (!NumberUtil.isNullOrZero(originalAmount) && validateOriginalAmount) {
        //         logRemark.append("，并重新置：").append(MoneyUtil.parseToYuanEndWithUnit(originalAmount));
        //     }
        //     if (StringUtils.isBlank(orderDTO.getOperatorLogRemark())) {
        //         orderDTO.setOperatorLogRemark(logRemark.toString());
        //     } else {
        //         orderDTO.setOperatorLogRemark(String.format("%s；%s", orderDTO.getOperatorLogRemark(), logRemark.toString()));
        //     }
        // }

        // 用户电话发生变更 小号需解绑再绑定
        boolean isPhoneChanged = !Objects.equals(dbOrderWorkDetail.getTelephone(), orderDetail.getTelephone());
        boolean isPhone2Changed = !Objects.equals(dbOrderWorkDetail.getTelephone2(), orderDetail.getTelephone2());
        boolean isPhone3Changed = !Objects.equals(dbOrderWorkDetail.getTelephone3(), orderDetail.getTelephone3());
        if (NumberUtil.isNotNullOrZero(dbOrderWork.getMasterId())
            && (isPhoneChanged || isPhone2Changed || isPhone3Changed)) {
            XnoBindDTO xnoBindDTO = new XnoBindDTO();
            xnoBindDTO.setOrderId(orderWork.getOrderId());
            xnoBindDTO.setWorkId(orderWork.getWorkId());
            // 解绑号码
            xnoBindDTO.setUnBindMasterId(dbOrderWork.getMasterId());
            xnoBindDTO.setUnBindTelephone1(isPhoneChanged ? dbOrderWorkDetail.getTelephone() : null);
            xnoBindDTO.setUnBindTelephone2(isPhone2Changed ? dbOrderWorkDetail.getTelephone2() : null);
            xnoBindDTO.setUnBindTelephone3(isPhone3Changed ? dbOrderWorkDetail.getTelephone3() : null);
            orderXnoBindBService.bind(xnoBindDTO);
        }

        // // 冻结金额
        // if (isProductNumberChanged) {
        //     super.saveAgainFactoryFreezeAmount(orderDTO);
        // }

        // 更新工程师进行中订单信息
        super.saveMasterWorking(orderDTO.getOrderId(), orderDTO.getWorkId());

        // 工程师领单后，在变更预约时间 发送通知(暂时取消)
        //logger.info("{}工程师领单后，在变更预约时间，发送通知", orderWork.getOrderId());
        //sendOrderNoticeService.sendUpdateDutyTimeMessageNotice(orderWork, dbOrderWork);

        boolean latitudeOrLongitudeChanged = !Objects.equals(orderDetail.getLatitude(), dbOrderWorkDetail.getLatitude())
                || !Objects.equals(orderDetail.getLongitude(), dbOrderWorkDetail.getLongitude());
        boolean dutyTimeChanged = !Objects.equals(orderWork.getDutyTime(), dbOrderWork.getDutyTime());
        if (channelChanged || latitudeOrLongitudeChanged || isShowProductIdChanged || isProductChanged || dutyTimeChanged) {
            // 移除抢单
            if (Objects.equals(dbOrderWork.getGrabType(), GlobalConsts.YES)) {
                OrderWorkGrabDTO orderWorkGrabDTO = BeanMapper.map(orderDTO, OrderWorkGrabDTO.class);
                orderWorkGrabDTO.setGrabType(GlobalConsts.NONE);
                orderWorkGrabDTO.setAutoFlow(false);
                // 判断是否无网格抢单
                NonGridGrabOrderQuery query = new NonGridGrabOrderQuery();
                query.setOrderId(orderWorkGrabDTO.getOrderId());
                query.setWorkId(orderWorkGrabDTO.getWorkId());
                query.setValidStatus(com.zmn.consts.GlobalConsts.YES);
                List<NonGridGrabOrder> nonGridGrabOrderList = nonGridGrabOrderService.listByQuery(query);
                if (CollectionUtil.isNullOrEmpty(nonGridGrabOrderList)) {
                    orderWorkGrabBService.saveGrabType(orderWorkGrabDTO);
                }
            }
        }

        // 重新判断无网格抢单，无网格抢单只要修改就移出抢单池
        if (Objects.equals(dbOrderWork.getGrabType(), com.zmn.consts.GlobalConsts.YES)) {
            OrderWorkGrabDTO orderWorkGrabDTO = BeanMapper.map(orderDTO, OrderWorkGrabDTO.class);
            orderWorkGrabDTO.setGrabType(com.zmn.consts.GlobalConsts.NO);
            NonGridGrabOrderQuery query = new NonGridGrabOrderQuery();
            query.setOrderId(orderDTO.getOrderId());
            query.setWorkId(orderDTO.getWorkId());
            query.setValidStatus(com.zmn.consts.GlobalConsts.YES);
            List<NonGridGrabOrder> nonGridGrabOrderList = nonGridGrabOrderService.listByQuery(query);
            if (CollectionUtil.isNotNullOrEmpty(nonGridGrabOrderList)) {
                nonGridGrabOrderBService.modifyGrabType(orderWorkGrabDTO);
            }
        }

        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) && (isProductChanged || isShowProductIdChanged)) {
            orderQuotation3ModifyBService.clearQuotationInfo(orderDTO.getOrderId(), orderDTO.getWorkId(), true);
        }

        return orderBO;
    }

    /**
     * 发送订单预约交换站内信
     *
     * @param orderDTO 修改订单对象
     * @param orderWork 修改订单信息
     * @param dbOrderWork 当前订单原始信息
     */
    private void sendOrderDutyExchangeAppMsg(OrderDTO orderDTO, OrderWork orderWork, OrderWork dbOrderWork) {
        // 发送消息通知
        Map<String, String> params = Maps.newHashMap();
        params.put("master_name", dbOrderWork.getMasterName());
        params.put("order_id", String.valueOf(orderDTO.getOrderId()));
        params.put("duty_time", DateUtil.toString(dbOrderWork.getDutyTime(), "yyyy/M/dd HH:mm"));
        params.put("exchange_order_id", String.valueOf(orderDTO.getExchangeWorkId()));
        params.put("exchange_duty_time", DateUtil.toString(orderWork.getDutyTime(), "yyyy/M/dd HH:mm"));
        log.info("#ZsOrderBServiceImpl#sendOrderDutyExchangeAppMsg:{}", JSON.toJSONString(params));
        messageSendAppService.pushAppMessageInfo(MessageConsts.ZMN_MSG_RULEID_ORDER_DUTYTIME_EXCHANGE, JSON.toJSONString(params), dbOrderWork);
    }

    /**
     * 保存网格信息
     * @param orderDTO
     * @return
     */
    private void saveGridInfo(OrderDTO orderDTO, Integer logType) {

        OrderWork orderWork = orderDTO.getOrderWork();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
//        orderDetail.setGridId(0);
//        orderDetail.setGridName("");
//        if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
//            orderDetail.setGridManageCompanyId(0);
//            orderDetail.setGridManageCompanyName("");
//        } else {
//            orderDetail.setGridManageCompanyId(0);
//            orderDetail.setGridManageCompanyName("");
//            orderDetail.setGridCompanyId(0);
//            orderDetail.setGridCompanyName("");
//
//            // 如果服务商派单没有预分配服务商，塞默认行政服务商，只判断后台下单
//            boolean backStage = Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_SP)
//                    && Objects.isNull(orderDTO.getPreManageCompanyId())
//                    && Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_INPUT)
//                    && (Objects.equals(orderWork.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CC)
//                    || Objects.equals(orderWork.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CHAT)
//                    || Objects.equals(orderWork.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_BACKSTAGE));
//            if (backStage) {
//                if (Objects.equals(orderWork.getPlatWork(), com.zmn.consts.GlobalConsts.PLAT_MARK_YEYX)) {
//                    orderDetail.setGridManageCompanyId(CompanyConsts.YEYX_SPECIAL_MANAGE_COMPANY_ID);
//                    orderDetail.setGridManageCompanyName("远程指导专家组");
//                    orderDetail.setGridCompanyId(CompanyConsts.YEYX_CHONGQING_COMPANY_ID);
//                    orderDetail.setGridCompanyName("重庆公司");
//                } else if (Objects.equals(orderWork.getPlatWork(), com.zmn.consts.GlobalConsts.PLAT_MARK_CNHB)) {
//                    orderDetail.setGridManageCompanyId(CompanyConsts.CNHB_SPECIAL_MANAGE_COMPANY_ID);
//                    orderDetail.setGridManageCompanyName("川南暂无服务商");
//                    orderDetail.setGridCompanyId(CompanyConsts.CNHB_NATIONWIDE_COMPANY_ID);
//                    orderDetail.setGridCompanyName("川南子公司-全国");
//                } else {
//                    orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
//                    orderDetail.setGridManageCompanyName("无法承接线索");
//                    orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
//                    orderDetail.setGridCompanyName("无法服务");
//                }
//            }
//        }
//
//        ResponseDTO<GridSpDRO> responseDTO = null;
//        try {
//            log.info("[{}]-查询网格信息入参：[{}]-[{}]-[{}]-[{}]", orderWork.getOrderId(), orderDetail.getLongitude(),
//                    orderDetail.getLatitude(), orderWork.getServCategId(), orderWork.getShowCategId());
//            responseDTO = gridOrderListRemoteService.listGridSpByLatLngAndCategoryId(
//                    orderDetail.getLongitude(), orderDetail.getLatitude(), String.valueOf(orderWork.getServCategId()),
//                    String.valueOf(orderWork.getShowCategId()));
//            log.info("[{}]-查询网格信息出参：[{}]", orderWork.getOrderId(), JSON.toJSONString(responseDTO));
//            if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())) {
//                orderDetail.setGridId(responseDTO.getData().getGridId());
//                orderDetail.setGridName(responseDTO.getData().getGridName());
//                if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
//                    orderDetail.setGridManageCompanyId(responseDTO.getData().getSpId());
//                    orderDetail.setGridManageCompanyName(responseDTO.getData().getSpName());
//                }
//            }
//        } catch (Exception ex) {
//            log.error("[{}]-查询网格信息异常：[{}]", orderWork.getOrderId(), ex.getMessage());
//        }
//
//        // 下单或服务商派单直接退出，以下是平台直派修改和服务商改地址操作
//        if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_SP)) {
//            return;
//        }
//
//        /**
//         * 行政服务商规则：
//         * 1、下单地址是否划分了网格，没有提示暂无网格覆盖，行政服务商默认塞无法承接线索
//         * 2、网格是否有子公司满足，满足看4，不满足看3
//         * 3、家修匠的服务商是否满足，满足提示行政服务商，行政子公司为家修匠，不满足提示无法承接线索
//         * 4、网格是否有服务商满足，服务商的上级是否是第二步查出的子公司，是提示行政服务商，不是提示行政子公司
//         */
//        if (NumberUtil.isNullOrZero(orderDetail.getGridId())) {
//            orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
//            orderDetail.setGridCompanyName("无法服务");
//            orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
//            orderDetail.setGridManageCompanyName("无法承接线索");
//        } else {
//
//            Integer gridCompanyId = null;
//            String gridCompanyName = null;
//
//            CompanyGridInfoDIO dio = new CompanyGridInfoDIO();
//            dio.setGridId(orderDetail.getGridId());
//            dio.setFirstCategoryId(orderWork.getServCategId());
//            dio.setSecondCategoryId(orderWork.getShowCategOneId());
//            dio.setThirdCategoryId(orderWork.getShowCategId());
//            log.info("[{}]-查询行政子公司入参：[{}]", orderWork.getOrderId(), JSON.toJSONString(dio));
//            ResponseDTO<CompanyGridInfoDRO> gridCompanyResponseDTO = companyGridListRemoteService.getCompanyInfoByGridIdAndCategoryId(dio);
//            log.info("[{}]-查询行政子公司出参：[{}]", orderWork.getOrderId(), JSON.toJSONString(gridCompanyResponseDTO));
//            if (gridCompanyResponseDTO.isSuccess() && Objects.nonNull(gridCompanyResponseDTO.getData())) {
//                gridCompanyId = gridCompanyResponseDTO.getData().getCompanyId();
//                gridCompanyName = gridCompanyResponseDTO.getData().getCompanyName();
//            }
//
//            // 如果行政服务商不是空，查询服务商的上级子公司
//            if (NumberUtil.isNotNullOrZero(orderDetail.getGridManageCompanyId())) {
//                // 获取公司信息
//                ResponseDTO<CompanyDRO> companyResponseDTO = baseCompanyListRemoteService.getCompanyByCompanyId(orderDetail.getGridManageCompanyId());
//                log.info("[{}]-获取公司信息出参：[{}]", orderWork.getOrderId(), JSON.toJSONString(companyResponseDTO));
//
//                if (NumberUtil.isNullOrZero(gridCompanyId)) {
//                    // 行政子公司为空，判断服务商是否属于家修匠
//                    if (Objects.equals(companyResponseDTO.getData().getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID)) {
//                        orderDetail.setGridCompanyId(CompanyConsts.ZMN_JXJ_COMPANY_ID);
//                        orderDetail.setGridCompanyName("家修匠");
//                    } else {
//                        // 不属于家修匠，塞无法承接线索
//                        orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
//                        orderDetail.setGridCompanyName("无法服务");
//                        orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
//                        orderDetail.setGridManageCompanyName("无法承接线索");
//                    }
//                } else {
//                    // 行政子公司不为空直接塞入
//                    orderDetail.setGridCompanyId(gridCompanyId);
//                    orderDetail.setGridCompanyName(gridCompanyName);
//                    // 如果行政服务商上级不是绑定子公司，则把行政服务商清掉
//                    if (!Objects.equals(companyResponseDTO.getData().getSubCompanyId(), gridCompanyId)) {
//                        orderDetail.setGridManageCompanyId(0);
//                        orderDetail.setGridManageCompanyName("");
//                    }
//                }
//            } else {
//                // 行政子公司不为空直接塞入
//                if (NumberUtil.isNotNullOrZero(gridCompanyId)) {
//                    orderDetail.setGridCompanyId(gridCompanyId);
//                    orderDetail.setGridCompanyName(gridCompanyName);
//                } else {
//                    // 行政子公司和行政服务商都为空，默认塞无法承接线索
//                    orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
//                    orderDetail.setGridCompanyName("无法服务");
//                    orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
//                    orderDetail.setGridManageCompanyName("无法承接线索");
//                }
//            }
//        }

        GridCompanyQueryBO gridCompanyQueryBO = new GridCompanyQueryBO();
        gridCompanyQueryBO.setCityId(orderWork.getCityId());
        gridCompanyQueryBO.setDistributeWay(orderWork.getDistributeWay());
        gridCompanyQueryBO.setLatitude(orderDetail.getLatitude());
        gridCompanyQueryBO.setLongitude(orderDetail.getLongitude());
        gridCompanyQueryBO.setGridCompanyId(orderDetail.getGridCompanyId());
        gridCompanyQueryBO.setGridManageCompanyId(orderDetail.getGridManageCompanyId());
        gridCompanyQueryBO.setServCategId(orderWork.getServCategId());
        gridCompanyQueryBO.setShowCategId(orderWork.getShowCategId());
        gridCompanyQueryBO.setShowCategOneId(orderWork.getShowCategOneId());
        gridCompanyQueryBO.setPreManageCompanyId(orderDTO.getPreManageCompanyId());
        gridCompanyQueryBO.setPlatWork(orderWork.getPlatWork());
        gridCompanyQueryBO.setOrderId(orderWork.getOrderId());
        gridCompanyQueryBO.setLogType(logType);
        GridCompanyInfoDTO gridCompanyInfo = this.getGridCompanyInfo(gridCompanyQueryBO);
        log.info("[{}]-处理行政子公司/服务商结果：【{}】", orderWork.getOrderId(), JSON.toJSONString(gridCompanyInfo));

        // 赋值orderDetail
        orderDetail.setGridId(gridCompanyInfo.getGridId());
        orderDetail.setGridName(gridCompanyInfo.getGridName());
        orderDetail.setGridCompanyId(gridCompanyInfo.getGridCompanyId());
        orderDetail.setGridCompanyName(gridCompanyInfo.getGridCompanyName());
        orderDetail.setGridManageCompanyId(gridCompanyInfo.getGridManageCompanyId());
        orderDetail.setGridManageCompanyName(gridCompanyInfo.getGridManageCompanyName());

        // 下单或服务商派单直接退出，以下是平台直派修改和服务商改地址操作
        if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_SP)) {
            return;
        }

        // 冗余行政组织架构
        this.processGridOrg(orderDTO, orderDetail, logType);

        /*if (responseDTO == null) {
            this.processGridOrg(orderDTO, orderDetail.getGridCompanyId(), orderDetail.getGridManageCompanyId(), logType);
            return;
        }

        GridSpDRO dro = responseDTO.getData();
        orderDetail.setGridId(dro.getGridId());
        orderDetail.setGridName(dro.getGridName());

        // 没有绑定服务商，默认塞无法承接线索
        if (StringUtil.isBlank(dro.getSpName())) {
            this.processGridOrg(orderDTO, orderDetail.getGridCompanyId(), orderDetail.getGridManageCompanyId(), logType);
            return;
        }

        orderDetail.setGridManageCompanyId(dro.getSpId());
        orderDetail.setGridManageCompanyName(dro.getSpName());

        log.debug("[{}]查找行政子公司信息：入参：{}", orderWork.getOrderId(), dro.getSpId());
        ResponseDTO<CompanyDRO> companyResponseDTO = baseCompanyListRemoteService.getCompanyByCompanyId(dro.getSpId());
        log.debug("[{}]查找行政子公司信息：出参：{}", orderWork.getOrderId(), JSON.toJSONString(companyResponseDTO));
        if (!companyResponseDTO.isSuccess() || Objects.isNull(companyResponseDTO.getData())) {
            this.processGridOrg(orderDTO, orderDetail.getGridCompanyId(), orderDetail.getGridManageCompanyId(), logType);
            return;
        }

        orderDetail.setGridCompanyId(companyResponseDTO.getData().getSubCompanyId());
        orderDetail.setGridCompanyName(companyResponseDTO.getData().getSubCompanyName());
        this.processGridOrg(orderDTO, orderDetail.getGridCompanyId(), orderDetail.getGridManageCompanyId(), logType);*/
    }

    /**
     * 处理行政服务商的组织架构信息
     * @param orderDTO
     * @param orderDetail
     * @param logType
     */
    private void processGridOrg(OrderDTO orderDTO, OrderDetail orderDetail, Integer logType) {

        // 录单通过消息异步插入行政组织架构
        if (Objects.equals(logType, OrderLogConsts.ORDER_LOG_TYPE_INPUT)) {
            return;
        }

        OrderWorkOperatorDTO dto = BeanMapper.map(orderDTO, OrderWorkOperatorDTO.class);
        if (NumberUtil.isNotNullOrZero(orderDetail.getGridCompanyId())) {
            // 获取公司信息
            ResponseDTO<CompanyDRO> companyResponseDTO = companyListRemoteService.getCompanyDROById(orderDetail.getGridCompanyId());
            logger.debug("[{}]获取公司信息出参[{}]", orderDTO.getWorkId(), JSON.toJSONString(companyResponseDTO));
            if (!companyResponseDTO.isSuccess() || Objects.isNull(companyResponseDTO.getData())) {
                return;
            }
            CompanyDRO companyDRO = companyResponseDTO.getData();

            dto.setGridOrgOneId(companyDRO.getPlat());
            dto.setGridOrgTwoId(companyDRO.getOrgTwoId());
            dto.setGridOrgThreeId(companyDRO.getOrgThrId());
            dto.setGridOrgFourId(orderDetail.getGridManageCompanyId());
        } else {
            dto.setGridOrgOneId(0);
            dto.setGridOrgTwoId(0);
            dto.setGridOrgThreeId(0);
            dto.setGridOrgFourId(0);
        }
        orderWorkOperatorBService.insertOrUpdateOperator(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBO insertOrder(OrderDTO orderDTO) throws OmsBaseException {

        // 处理下单默认服务项
        orderBService.processPlaceAnOrderDefaultServItem(orderDTO);

        // 设置服务合同模式
        Integer workPlat = platBizModeService.findByPlat(orderDTO.getOrderWork().getPlatWork());
        orderDTO.getOrderWork().setBizMode(workPlat);

        Integer plat = platBizModeService.findByPlat(orderDTO.getOrderWork().getPlat());
        orderDTO.getOrderWork().setBizModeSource(plat);

        boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(orderDTO.getOrderWork());
        if (isGrid) {
            orderDTO.getOrderWork().setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
        } else {
            orderDTO.getOrderWork().setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
        }
        // 下单保存网格id、行政服务商、行政子公司
        this.saveGridInfo(orderDTO, OrderLogConsts.ORDER_LOG_TYPE_INPUT);

        return  orderBService.insertOrder(orderDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_UPDATE_ADDRESS, beforeProceed = false)
    public OrderBO updateAddress(OrderDTO orderDTO) throws OmsBaseException {
        // 订单信息
        OrderWork orderWork = orderDTO.getOrderWork();

        // 原始数据
        OrderWork dbOrderWork = Optional.ofNullable(orderDTO.getDbOrderWork())
                .orElse(orderWorkService.findOrderWorkByKey(orderWork.getOrderId(), orderWork.getWorkId()));
        OrderDetail dbOrderWorkDetail = Optional.ofNullable(orderDTO.getDbOrderDetail())
                .orElse(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()));

        // 用来判断派单模式
        orderWork.setPlatWork(dbOrderWork.getPlatWork());
        orderWork.setManageCompanyId(dbOrderWork.getManageCompanyId());
        if (NumberUtil.isNullOrZero(orderWork.getCityId())) {
            orderWork.setCityId(dbOrderWork.getCityId());
        }
        orderWork.setBizType(dbOrderWork.getBizType());
        orderWork.setServProductGroupId(dbOrderWork.getServProductGroupId());
        orderWork.setServCategId(dbOrderWork.getServCategId());
        orderWork.setShowCategId(dbOrderWork.getShowCategId());
        orderWork.setShowCategOneId(dbOrderWork.getShowCategOneId());

        // 服务商派单修改不更新网格信息
        boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(orderWork);
        if (isGrid) {
            // 服务商修改地址保存网格id、行政服务商、行政子公司
            orderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
            this.saveGridInfo(orderDTO, OrderLogConsts.ORDER_LOG_TYPE_UPDATE_ADDRESS);
        } else {
            orderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
        }

        orderDTO.setDbOrderDetail(dbOrderWorkDetail);
        orderDTO.setDbOrderWork(dbOrderWork);

        // 保修地址修改
        OrderBO orderBO = orderBService.updateOrderAddress(orderDTO);

        return orderBO;
    }

    /**
     * 用户新增不认领订单
     * @param nonClaimOrderDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_NOT_CLAIM_ORDER, beforeProceed = false)
    public void insertNonClaimOrder(NonClaimOrderDTO nonClaimOrderDTO) {
        NonClaimOrder order = new NonClaimOrder();
        order.setOrderId(nonClaimOrderDTO.getOrderId());
        order.setUserId(nonClaimOrderDTO.getUserId());
        order.setTelephone(nonClaimOrderDTO.getTelephone());
        order.setCreater(nonClaimOrderDTO.getOperator());
        order.setUpdater(nonClaimOrderDTO.getOperator());
        Date date = DateUtil.getNow();
        order.setCreateTime(date);
        order.setUpdateTime(date);
        nonClaimOrderService.insertNonClaimOrder(order);
    }

    /**
     * 订单分单撤回
     *
     * @param orderDTO
     */
    private boolean isTypeChange(OrderDTO orderDTO) {
        OrderWork dbOrderWork = orderDTO.getDbOrderWork();
        OrderWork orderWork = orderDTO.getOrderWork();
        return (Objects.equals(dbOrderWork.getType(), OrderConsts.ORDER_TYPE_NEW) && (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)))
                || (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) && (Objects.equals(dbOrderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)));
    }

    private boolean updateServiceItemType(OrderWork orderWork, OrderWork dbOrderWork) {
        // 新旧服务项类型
        Integer oldServiceItemType = dbOrderWork.getServItemType();

        CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = BeanMapper.map(orderWork, CheckQuotationTypeOrderDTO.class);
        checkQuotationTypeOrderDTO.setCompanyId(dbOrderWork.getCompanyId());
        checkQuotationTypeOrderDTO.setMasterId(dbOrderWork.getMasterId());
        checkQuotationTypeOrderDTO.setBeforeServItemType(dbOrderWork.getServItemType());
        checkQuotationTypeOrderDTO.setCompatibilityFinalPrice(false);
        logger.info("[{}]修改计价类型[{}]", orderWork.getWorkId(), checkQuotationTypeOrderDTO);
        Integer newServiceItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO);
        logger.info("[{}]修改计价类型，旧类型[{}]-->新类型[{}]", orderWork.getWorkId(), oldServiceItemType, newServiceItemType);
        // 不同，更新服务项类型
        if (!Objects.equals(newServiceItemType, oldServiceItemType)) {
            OrderWork updateWork = new OrderWork();
            updateWork.setOrderId(orderWork.getOrderId());
            updateWork.setWorkId(orderWork.getWorkId());
            // servItemType==5的修改成4，并且标识一口价（一口价订单需求兼容app走计价器3.0流程）
            if (Objects.equals(newServiceItemType, OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)) {
                updateWork.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
                updateWork.setFinalPrice(GlobalConsts.YES);
            }else {
                updateWork.setFinalPrice(GlobalConsts.NO);
            }
            updateWork.setUpdateTime(new Date());

            orderWorkService.updateOrderServItemTypeByKey(updateWork);
            return true;
        }
        // 如果产品、渠道、城市有修改，计价器类型工单仍需要重新设置服务项
        if (Objects.equals(newServiceItemType, OrderConsts.COMMENT_TYPE_DEFAULT)) {
            return true;
        }

        return false;
    }

    /**
     * @param gridCompanyQueryBO
     * @return
     */
    @Override
    public GridCompanyInfoDTO getGridCompanyInfo(GridCompanyQueryBO gridCompanyQueryBO) {
        log.info("获取网格服务公司信息入参：{}", gridCompanyQueryBO);
        GridCompanyInfoDTO gridCompanyInfoDTO = new GridCompanyInfoDTO();
        gridCompanyInfoDTO.setGridId(0);
        gridCompanyInfoDTO.setGridName("");
        if (Objects.equals(gridCompanyQueryBO.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
            gridCompanyInfoDTO.setGridManageCompanyId(0);
            gridCompanyInfoDTO.setGridManageCompanyName("");
        } else {
            gridCompanyInfoDTO.setGridManageCompanyId(0);
            gridCompanyInfoDTO.setGridManageCompanyName("");
            gridCompanyInfoDTO.setGridCompanyId(0);
            gridCompanyInfoDTO.setGridCompanyName("");

            if (Objects.equals(gridCompanyQueryBO.getPlatWork(), com.zmn.consts.GlobalConsts.PLAT_MARK_YEYX)) {
                gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.YEYX_SPECIAL_MANAGE_COMPANY_ID);
                gridCompanyInfoDTO.setGridManageCompanyName("远程指导专家组");
                gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.YEYX_CHONGQING_COMPANY_ID);
                gridCompanyInfoDTO.setGridCompanyName("重庆公司");
            } else if (Objects.equals(gridCompanyQueryBO.getPlatWork(), com.zmn.consts.GlobalConsts.PLAT_MARK_CNHB)) {
                gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.CNHB_SPECIAL_MANAGE_COMPANY_ID);
                gridCompanyInfoDTO.setGridManageCompanyName("川南暂无服务商");
                gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.CNHB_NATIONWIDE_COMPANY_ID);
                gridCompanyInfoDTO.setGridCompanyName("川南子公司-全国");
            } else {
                gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
                gridCompanyInfoDTO.setGridManageCompanyName("无法服务线索");
                gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
                gridCompanyInfoDTO.setGridCompanyName("无法服务");
            }
        }

        ResponseDTO<GridSpDRO> responseDTO = null;
        try {
            log.info("[{}]-查询网格信息入参：[{}]-[{}]-[{}]-[{}]", gridCompanyQueryBO.getOrderId(), gridCompanyQueryBO.getLongitude(),
                    gridCompanyQueryBO.getLatitude(), gridCompanyQueryBO.getServCategId(), gridCompanyQueryBO.getShowCategId());
            responseDTO = gridOrderListRemoteService.listGridSpByLatLngAndCategoryId(
                    gridCompanyQueryBO.getLongitude(), gridCompanyQueryBO.getLatitude(), String.valueOf(gridCompanyQueryBO.getServCategId()),
                    String.valueOf(gridCompanyQueryBO.getShowCategId()));
            log.info("[{}]-查询网格信息出参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(responseDTO));
            if (responseDTO.isSuccess() && Objects.nonNull(responseDTO.getData())) {
                gridCompanyInfoDTO.setGridId(responseDTO.getData().getGridId());
                gridCompanyInfoDTO.setGridName(responseDTO.getData().getGridName());
                if (Objects.equals(gridCompanyQueryBO.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
                    // 下单有行政子公司和服务商，查询子公司/服务商名称
                    if (NumberUtil.isNotNullOrZero(gridCompanyQueryBO.getGridCompanyId())) {
                        gridCompanyInfoDTO.setGridManageCompanyId(gridCompanyQueryBO.getGridManageCompanyId());
                        ResponseDTO<SpServProviderDRO> spResponseDTO = spManageListRemoteService.getServProviderById(gridCompanyQueryBO.getGridManageCompanyId());
                        if (spResponseDTO.isSuccess() && Objects.nonNull(spResponseDTO.getData())) {
                            gridCompanyInfoDTO.setGridManageCompanyName(spResponseDTO.getData().getName());
                        }
                        gridCompanyInfoDTO.setGridCompanyId(gridCompanyQueryBO.getGridCompanyId());
                        // 获取公司信息
                        ResponseDTO<CompanyDRO> companyResponseDTO = companyListRemoteService.getCompanyDROById(gridCompanyQueryBO.getGridCompanyId());
                        if (companyResponseDTO.isSuccess() && Objects.nonNull(companyResponseDTO.getData())) {
                            gridCompanyInfoDTO.setGridCompanyName(companyResponseDTO.getData().getName());
                        }
                        return gridCompanyInfoDTO;
                    } else {
                        if (NumberUtil.isNotNullOrZero(responseDTO.getData().getSpId())) {
                            gridCompanyInfoDTO.setGridManageCompanyId(responseDTO.getData().getSpId());
                            gridCompanyInfoDTO.setGridManageCompanyName(responseDTO.getData().getSpName());
                        }
                    }
                }
            }
        } catch (Exception ex) {
            log.error("[{}]-查询网格信息异常：[{}]", gridCompanyQueryBO.getOrderId(), ex.getMessage());
        }

        // 下单或服务商派单直接退出，以下是平台直派修改和服务商改地址操作
        if (Objects.equals(gridCompanyQueryBO.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_SP)) {
            return gridCompanyInfoDTO;
        }

        /**
         * 行政服务商规则：
         * 1、下单地址是否划分了网格，没有提示暂无网格覆盖，行政服务商默认塞无法承接线索
         * 2、网格是否有子公司满足，满足看4，不满足看3
         * 3、家修匠的服务商是否满足，满足提示行政服务商，行政子公司为家修匠，不满足提示无法承接线索
         * 4、网格是否有服务商满足，服务商的上级是否是第二步查出的子公司，是提示行政服务商，不是提示行政子公司
         */
        if (NumberUtil.isNullOrZero(gridCompanyInfoDTO.getGridId())) {
            gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
            gridCompanyInfoDTO.setGridCompanyName("无法服务");
            gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
            gridCompanyInfoDTO.setGridManageCompanyName("无法服务线索");
        } else {

            Integer gridCompanyId = null;
            String gridCompanyName = null;
            OrderServiceReason orderServiceReason = null;

            CompanyGridInfoDIO dio = new CompanyGridInfoDIO();
            dio.setGridId(gridCompanyInfoDTO.getGridId());
            dio.setFirstCategoryId(gridCompanyQueryBO.getServCategId());
            dio.setSecondCategoryId(gridCompanyQueryBO.getShowCategOneId());
            dio.setThirdCategoryId(gridCompanyQueryBO.getShowCategId());
            log.info("[{}]-查询行政子公司入参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(dio));
            ResponseDTO<CompanyGridInfoDRO> gridCompanyResponseDTO = companyGridListRemoteService.getCompanyInfoByGridIdAndCategoryId(dio);
            log.info("[{}]-查询行政子公司出参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(gridCompanyResponseDTO));
            if (gridCompanyResponseDTO.isSuccess() && Objects.nonNull(gridCompanyResponseDTO.getData())) {
                gridCompanyId = gridCompanyResponseDTO.getData().getCompanyId();
                gridCompanyName = gridCompanyResponseDTO.getData().getCompanyName();
            }

            // 如果行政服务商不是空，查询服务商的上级子公司
            if (NumberUtil.isNotNullOrZero(gridCompanyInfoDTO.getGridManageCompanyId())) {
                // 获取公司信息
                ResponseDTO<CompanyDRO> companyResponseDTO = companyListRemoteService.getCompanyDROById(gridCompanyInfoDTO.getGridManageCompanyId());
                log.info("[{}]-获取公司信息出参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(companyResponseDTO));

                if (NumberUtil.isNullOrZero(gridCompanyId)) {
                    // 行政子公司为空，判断服务商是否属于家修匠
                    if (Objects.equals(companyResponseDTO.getData().getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID)) {
                        gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_JXJ_COMPANY_ID);
                        gridCompanyInfoDTO.setGridCompanyName("家修匠");
                    } else {
                        // 不属于家修匠，塞无法承接线索
                        gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
                        gridCompanyInfoDTO.setGridCompanyName("无法服务");
                        gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
                        gridCompanyInfoDTO.setGridManageCompanyName("无法服务线索");
                    }
                } else {
                    // 行政子公司不为空直接塞入
                    gridCompanyInfoDTO.setGridCompanyId(gridCompanyId);
                    gridCompanyInfoDTO.setGridCompanyName(gridCompanyName);
                    // 如果行政服务商上级不是绑定子公司，则把行政服务商清掉
                    if (!Objects.equals(companyResponseDTO.getData().getSubCompanyId(), gridCompanyId)) {
                        // 查询子公司下信息公司
                        SpServProviderQuery spQuery = new SpServProviderQuery();
                        spQuery.setSubCompanyId(gridCompanyId);
                        spQuery.setThirdType(CompanyConst.COMPANY_TYPE_SERVICE_OCO);
                        spQuery.setStatus(com.zmn.consts.GlobalConsts.YES);
                        ResponseDTO<LayuiTableDO<SpServProviderDRO>> manageCompanyResponseDTO = spManageListRemoteService.listPageByQuery(spQuery);
                        log.info("[{}]-查询行政服务商信息公司入参：[{}]，出参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(spQuery), JSON.toJSONString(manageCompanyResponseDTO));
                        if (manageCompanyResponseDTO.isSuccess() && Objects.nonNull(manageCompanyResponseDTO.getData())
                                && CollectionUtil.isNotNullOrEmpty(manageCompanyResponseDTO.getData().getData())) {
                            SpServProviderDRO dro = manageCompanyResponseDTO.getData().getData().get(0);
                            gridCompanyInfoDTO.setGridManageCompanyId(dro.getSpId());
                            gridCompanyInfoDTO.setGridManageCompanyName(dro.getName());
                            if (Objects.equals(gridCompanyQueryBO.getLogType(), OrderLogConsts.ORDER_LOG_TYPE_INPUT)) {
                                // 网格没有行政服务商，通过行政子公司查询信息公司需要记录下
                                orderServiceReason = new OrderServiceReason();
                                orderServiceReason.setInGridspScopeService(com.zmn.consts.GlobalConsts.NO);
                            }
                        } else {
                            gridCompanyInfoDTO.setGridManageCompanyId(0);
                            gridCompanyInfoDTO.setGridManageCompanyName("");
                        }
                    }
                }
            } else {
                // 行政子公司不为空直接塞入
                if (NumberUtil.isNotNullOrZero(gridCompanyId)) {
                    gridCompanyInfoDTO.setGridCompanyId(gridCompanyId);
                    gridCompanyInfoDTO.setGridCompanyName(gridCompanyName);

                    // 查询子公司下信息公司
                    SpServProviderQuery spQuery = new SpServProviderQuery();
                    spQuery.setSubCompanyId(gridCompanyId);
                    spQuery.setThirdType(CompanyConst.COMPANY_TYPE_SERVICE_OCO);
                    spQuery.setStatus(com.zmn.consts.GlobalConsts.YES);
                    ResponseDTO<LayuiTableDO<SpServProviderDRO>> manageCompanyResponseDTO = spManageListRemoteService.listPageByQuery(spQuery);
                    log.info("[{}]-查询行政服务商信息公司入参：[{}]，出参：[{}]", gridCompanyQueryBO.getOrderId(), JSON.toJSONString(spQuery), JSON.toJSONString(manageCompanyResponseDTO));
                    if (manageCompanyResponseDTO.isSuccess() && Objects.nonNull(manageCompanyResponseDTO.getData())
                            && CollectionUtil.isNotNullOrEmpty(manageCompanyResponseDTO.getData().getData())) {
                        SpServProviderDRO dro = manageCompanyResponseDTO.getData().getData().get(0);
                        gridCompanyInfoDTO.setGridManageCompanyId(dro.getSpId());
                        gridCompanyInfoDTO.setGridManageCompanyName(dro.getName());
                        if (Objects.equals(gridCompanyQueryBO.getLogType(), OrderLogConsts.ORDER_LOG_TYPE_INPUT)) {
                            // 网格没有行政服务商，通过行政子公司查询信息公司需要记录下
                            orderServiceReason = new OrderServiceReason();
                            orderServiceReason.setInGridspScopeService(com.zmn.consts.GlobalConsts.NO);
                        }
                    }
                } else {
                    List<TagsDRO> list = baseCodeService.listBaseCodeMap(com.zmn.consts.GlobalConsts.PLAT_MARK_ZMN, OrderConsts.BASE_CODE_MAP_ONE_TYPE_JXJ_UN_SERVICE_CITY, gridCompanyQueryBO.getCityId(), null);
                    if (CollectionUtil.isNotNullOrEmpty(list)) {
                        // 行政子公司和行政服务商都为空，默认塞无法承接线索
                        gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_JXJ_COMPANY_ID);
                        gridCompanyInfoDTO.setGridCompanyName("家修匠");
                        gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
                        gridCompanyInfoDTO.setGridManageCompanyName("无法承接线索");
                    } else {
                        // 不属于家修匠，塞无法服务
                        gridCompanyInfoDTO.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
                        gridCompanyInfoDTO.setGridCompanyName("无法服务");
                        gridCompanyInfoDTO.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
                        gridCompanyInfoDTO.setGridManageCompanyName("无法服务线索");
                    }
                }
            }
            if (Objects.nonNull(orderServiceReason) && NumberUtil.isNotNullOrZero(gridCompanyQueryBO.getOrderId())) {
                orderServiceReason.setWorkId(gridCompanyQueryBO.getOrderId());
                orderServiceReason.setOrderId(gridCompanyQueryBO.getOrderId());
                orderServiceReason.setCreater("系统");
                orderServiceReason.setUpdater("系统");
                orderServiceReasonService.insert(orderServiceReason);

                // 保存信息公司兜底标记
                OrderTag orderTag = new OrderTag();
                orderTag.setOrderId(gridCompanyQueryBO.getOrderId());
                orderTag.setWorkId(gridCompanyQueryBO.getOrderId());
                orderTag.setTagType(OrderTagConsts.ORDER_TAG_USER_STAFF);
                orderTag.setTagId(OrderTagConsts.TAG_ID_OCO_COMPANY);
                orderTag.setTagName(OrderTagConsts.getTagName(OrderTagConsts.TAG_ID_OCO_COMPANY));
                orderTag.setCreater("系统");
                orderTag.setUpdater("系统");
                orderTagService.insertOrderTag(orderTag);
            }
        }

        return gridCompanyInfoDTO;
    }

    @Override
    public boolean isHaveSameCancelOrder(UserDIO userDIO, List<OrderProductDTO> orderProductList) {
        // 查询是否有同电话，地址，品类的用户在24小时内下单并取消
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateUtil.FORMAT_DEFAULT);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = now.minusDays(1);
        OrderWorkQuery query = new OrderWorkQuery();
        query.setExistCompleteTime(com.zmn.consts.GlobalConsts.NO);
        query.setWorkResultStatusList(Lists.newArrayList(OrderStatusConsts.WORK_RESULT_FAIL, OrderStatusConsts.WORK_RESULT_DISCARD));
        query.setCancelTime(String.format("%s,%s", dtf.format(start), dtf.format(now)));

        // 电话相同
        List<String> phoneList = new ArrayList<>();
        if (StringUtil.isNotBlank(userDIO.getTelephone())) {
            phoneList.add(userDIO.getTelephone());
        }
        if (StringUtil.isNotBlank(userDIO.getTelephone2())) {
            phoneList.add(userDIO.getTelephone2());
        }
        if (StringUtil.isNotBlank(userDIO.getTelephone3())) {
            phoneList.add(userDIO.getTelephone3());
        }
        query.setConcatPhoneList(phoneList);

        // 地址相同
        query.setCityIdList(Lists.newArrayList(userDIO.getCityId()));

        // 产品信息
        List<Integer> productIdList = Lists.newArrayList();
        List<Integer> showProductIdList = Lists.newArrayList();
        orderProductList.stream().forEach(e -> {
            if (Objects.equals(e.getProductShowType(), BaseProductConsts.EC_SHOW_TYPE)) {
                showProductIdList.add(e.getShowProductId());
            }
            productIdList.add(e.getProductId());
        });
        if (CollectionUtil.isNotNullOrEmpty(productIdList)) {
            query.setProductIdList(productIdList);
        }
        if (CollectionUtil.isNotNullOrEmpty(showProductIdList)) {
            query.setShowProductIdList(showProductIdList);
        }
        query.setFailMapIdList(failMapIdList);
        List<ZsOrderWorkVO> zsOrderWorkVOS = zsOrderWorkQueryBService.listPageOrderWorkByQuery(query);
        return zsOrderWorkVOS.stream().anyMatch(e ->
                Objects.equals(e.getUserStreet(), userDIO.getStreet())
                        && Objects.equals(e.getUserAddress(), userDIO.getAddress())
        );
    }

}
